package handler

import (
	"github.com/APP/internal/models"
	"github.com/APP/internal/service/system_service"
	code "github.com/APP/pkg/response"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

type RoleHandler struct {
	roleService *system_service.RoleService
}

func NewRoleHandler() *RoleHandler {
	return &RoleHandler{
		roleService: system_service.NewRoleService(),
	}
}

// CreateRoleRequest 创建角色请求结构
type CreateRoleRequest struct {
	ParentID    *int64 `json:"parent_id"`
	RoleName    string `json:"role_name" binding:"required"`
	RoleCode    string `json:"role_code" binding:"required"`
	Description string `json:"description"`
	Status      int    `json:"status"`
	Sort        int    `json:"sort"`
}

// UpdateRoleRequest 更新角色请求结构
type UpdateRoleRequest struct {
	ParentID    *int64 `json:"parent_id"`
	RoleName    string `json:"role_name" binding:"required"`
	RoleCode    string `json:"role_code" binding:"required"`
	Description string `json:"description"`
	Status      int    `json:"status"`
	Sort        int    `json:"sort"`
}

// RoleListRequest 角色列表请求结构
type RoleListRequest struct {
	Page     int    `form:"page" binding:"min=1"`
	PageSize int    `form:"page_size" binding:"min=1,max=100"`
	RoleName string `form:"role_name"`
	RoleCode string `form:"role_code"`
	Status   *int   `form:"status"`
}

// AssignPermissionsRequest 分配权限请求结构
type AssignPermissionsRequest struct {
	PermissionIDs []int64 `json:"permission_ids" binding:"required"`
}

// CreateRole 创建角色
func (h *RoleHandler) CreateRole(c *gin.Context) {
	var req CreateRoleRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	role := &models.SysRole{
		ParentID:    req.ParentID,
		RoleName:    req.RoleName,
		RoleCode:    req.RoleCode,
		Description: req.Description,
		Status:      req.Status,
		Sort:        req.Sort,
		CreatedAt:   time.Now(),
		UpdatedAt:   time.Now(),
	}

	if req.Status == 0 {
		role.Status = 1 // 默认启用
	}

	createdRole, err := h.roleService.CreateRole(role)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}

	code.Respond(c, code.Success, createdRole)
}

// UpdateRole 更新角色
func (h *RoleHandler) UpdateRole(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	var req UpdateRoleRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	role := &models.SysRole{
		ID:          id,
		ParentID:    req.ParentID,
		RoleName:    req.RoleName,
		RoleCode:    req.RoleCode,
		Description: req.Description,
		Status:      req.Status,
		Sort:        req.Sort,
		UpdatedAt:   time.Now(),
	}

	updatedRole, err := h.roleService.UpdateRole(role)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, updatedRole)
}

// DeleteRole 删除角色
func (h *RoleHandler) DeleteRole(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	err = h.roleService.DeleteRole(id)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, idStr)
}

// GetRole 获取角色详情
func (h *RoleHandler) GetRole(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	role, err := h.roleService.GetRole(id)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, role)
}

// GetRoleList 获取角色列表
func (h *RoleHandler) GetRoleList(c *gin.Context) {
	var req RoleListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	// 设置默认值
	if req.Page == 0 {
		req.Page = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 10
	}

	roles, total, err := h.roleService.GetRoleList(req.Page, req.PageSize, req.RoleName, req.RoleCode, req.Status)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}

	result := gin.H{
		"list":      roles,
		"total":     total,
		"page":      req.Page,
		"page_size": req.PageSize,
	}
	code.Respond(c, code.Success, result)
}

// GetRoleTree 获取角色树形结构
func (h *RoleHandler) GetRoleTree(c *gin.Context) {
	roles, err := h.roleService.GetRoleTree()
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, roles)
}

// GetRoleChildren 获取角色的所有子角色
func (h *RoleHandler) GetRoleChildren(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	children, err := h.roleService.GetRoleChildren(id)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, children)
}

// GetRoleAncestors 获取角色的所有祖先角色
func (h *RoleHandler) GetRoleAncestors(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	ancestors, err := h.roleService.GetRoleAncestors(id)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, ancestors)
}

// AssignPermissions 为角色分配权限
func (h *RoleHandler) AssignPermissions(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	var req AssignPermissionsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	err = h.roleService.AssignPermissions(id, req.PermissionIDs)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, nil)
}

// GetRolePermissions 获取角色的权限列表
func (h *RoleHandler) GetRolePermissions(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	permissionIDs, err := h.roleService.GetRolePermissions(id)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, permissionIDs)
}

// RebuildRoleTree 重建角色树
func (h *RoleHandler) RebuildRoleTree(c *gin.Context) {
	err := h.roleService.RebuildRoleTree()
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, "角色树重建成功")
}

// ValidateRoleTree 验证角色树的完整性
func (h *RoleHandler) ValidateRoleTree(c *gin.Context) {
	err := h.roleService.ValidateRoleTree()
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, "角色树验证通过")
}
